﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Quartz;
using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
using DevDefined.OAuth.Tests;
using System.Web.Configuration;
using System.Configuration;
using System.Xml;
using C5;
using Common.Logging;
using System.IO;
using Quartz.Collection;
using Quartz.Impl;
using Quartz.Impl.Calendar;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Listener;
using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Util;
using Quartz.Job;


namespace WebApplication1
{
    public partial class Global : System.Web.HttpApplication
    {
        public static IScheduler _scheduler;

        INonceGenerator _nonceGenerator = new GuidNonceGenerator();

        public class GuidNonceGenerator : INonceGenerator
        {
            protected Random random = new Random();

            public string GenerateNonce(IOAuthConsumerContext context)
            {
                return Guid.NewGuid().ToString();
            }
        }


        public INonceGenerator NonceGenerator
        {
            get { return _nonceGenerator; }
            set { _nonceGenerator = value; }
        }


        public interface INonceGenerator
        {
            string GenerateNonce(IOAuthConsumerContext context);
        }

        IOAuthSession CreateMeshPlaceContext()
        {
            var consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = "RUpS6PU9Ei8sgA8wZaziIg",
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret = "RBy_yuomJpdX32f1TG3TjNMaq08",
                Token = "k6GQelVpDeKEgFCUPcLbDFbYGtV6Vev-",
                TokenSecret = "7gF4Uoidu95J0HBbekbNYQ5AebE"


            };

            consumerContext.Nonce = NonceGenerator.GenerateNonce(consumerContext);
            //consumerContext.NonceGenerator=

            return new OAuthSession(consumerContext)
                          .RequiresCallbackConfirmation();
        }



        protected void Application_Start(object sender, EventArgs e)
        {
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler();
            _scheduler.Start();
            AddJob();

        }

        public static void RequestPosts()
        {

            try
            {

                Global teste = new Global();

                IOAuthSession consumer = teste.CreateMeshPlaceContext();


                //Save to config file


                if (ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString() != "")
                {

                    MySqlConnection testCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
                    MySqlConnection testConTwo = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                    testCon.Open();
                    testConTwo.Open();

                    //Random random = new Random();
                    //int num = random.Next(1000);

                    string cmdTextZip = "SELECT * FROM Mesh_Zip";
                    MySqlCommand cmdZipCodes = new MySqlCommand(cmdTextZip, testCon);
                    MySqlDataReader theReader;
                    MySqlDataReader theReaderDataInZip;

                    theReader = cmdZipCodes.ExecuteReader();

                    List<string> theZipCodesList = new List<string>();

                    while (theReader.Read())
                    {

                        theZipCodesList.Add(theReader[0].ToString());


                    }

                    //  SearchAgain:

                 //   string WhatZipCurrently;
                   // string whatSearchTerm;

                    string prevNewValue;

                    long j = 0;
                    string whatZipNext;

                    while (j < theZipCodesList.Count)


                    //for (int j = 0; j < theZipCodesList.Count; j++)
                    {


                        j++;

                        try
                        {


                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Settings.xml"));

                            XmlNodeList WhatZipCurrently;
                            XmlNodeList whatSearchTerm;
                            XmlNodeList whatZipCount;
                           

                            
                            WhatZipCurrently = xmlDoc.GetElementsByTagName("theZipCodeRow");
                            whatSearchTerm = xmlDoc.GetElementsByTagName("Category");
                            whatZipCount = xmlDoc.GetElementsByTagName("ZipCodeCount");
                            
                            //WhatZipCurrently = ConfigurationManager.AppSettings["theZipCodeRow"].ToString();
                            //whatSearchTerm = ConfigurationManager.AppSettings["Category"].ToString();
                            

                            string theURL = "http://api.yelp.com/v2/search?term=" + whatSearchTerm.Item(0).InnerText + "&location=" + WhatZipCurrently.Item(0).InnerText;

                            prevNewValue = whatZipCount.Item(0).InnerText;
                            
                            int theNewValueZip = Convert.ToInt32(prevNewValue) + 1;
                            string newValueZip=Convert.ToString(theNewValueZip);
                            int thisValueZip = Convert.ToInt32(newValueZip);
                
                            whatZipNext=theZipCodesList[thisValueZip].ToString().PadLeft(5,'0');
                            string responseText="";

                            try
                            {

                                responseText=consumer.Request().Get().ForUrl(theURL).ToString();
                            }
                            catch(Exception whatExe)
                            {
                                if (whatExe.Message == "The remote server returned an error: (403) Forbidden.")
                                {
                                    return;
                                }
                                int theNewValue = Convert.ToInt32(prevNewValue) + 1;

                                XmlDocument xmlDocTwo = new XmlDocument();
                                xmlDocTwo.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.xml"));

                                //XmlNodeList WhatZipCurrently;
                                //XmlNodeList whatSearchTerm;

                                string newValue = Convert.ToString(theNewValue);


                                XmlNodeList node;
                                XmlNodeList node2;

                                node = xmlDocTwo.GetElementsByTagName("ZipCodeCount");

                                //XmlNode node = xmlDoc.SelectSingleNode("Root/Configuration/ZipCodeCount");
                                node.Item(0).InnerText = newValue;

                                int thisValue = Convert.ToInt32(newValue);

                                node2 = xmlDocTwo.GetElementsByTagName("theZipCodeRow");
                                node2.Item(0).InnerText = theZipCodesList[thisValue].ToString();

                                xmlDocTwo.Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.xml"));

                            }

                            JToken oToken = JObject.Parse(responseText);

                            JArray items = (JArray)oToken["businesses"];
                         
                            JObject item;
                            JToken jUrl;
                            JToken jPostTitle;
                            JToken jPostImageURL;
                            JToken jSnippet;
                            
                            for (int i = 0; i < items.Count; i++)
                            {
                                item = (JObject)items[i];
                                jUrl = (string)item["url"];
                                jPostTitle = (string)item["name"];
                                jPostImageURL = (string)item["image_url"];
                                jSnippet = (string)item["snippet_text"];

                                string jTheTitle;
                                string theSnip;
                                string jTheImageurl;

                                try
                                {
                                    jTheTitle = ((JValue)jPostTitle).Value.ToString().Replace("'", "''");
                                }
                                catch (Exception theExce)
                                {
                                    jTheTitle = "";
                                }


                                try
                                {
                                    theSnip = ((JValue)jSnippet).Value.ToString().Replace("'", "''");
                                }
                                catch (Exception theExce)
                                {
                                    theSnip = "";
                                }

                                try
                                {
                                    jTheImageurl = ((JValue)jPostImageURL).Value.ToString();
                                }
                                catch (Exception theExce)
                                {
                                    jTheImageurl = "";
                                }

                                DateTime todaysDate = DateTime.Now;

                                string jTheDate = todaysDate.ToString("yyyy/MM/dd");

                                string cmdText = "INSERT INTO Mesh_Post (Post_Title ,Post_Date,Post_Link,Post_ImgURL,Post_Description,Post_Zip_Locale,UserNo,CategoryTitle) Values ('" + jTheTitle + "','" + jTheDate.ToString() + "','" + ((JValue)jUrl).Value.ToString() + "','" + jTheImageurl + "','" + theSnip + "','" + WhatZipCurrently.Item(0).InnerText + "',320,'Volunteering')";
                                MySqlCommand cmd = new MySqlCommand(cmdText, testConTwo);

                                cmd.ExecuteNonQuery();

                                System.Threading.Thread.Sleep(1000);

                                if (i == items.Count - 1)
                                {

                                    int theNewValue = Convert.ToInt32(prevNewValue) + 1;
                                    
                                    XmlDocument xmlDocTwo = new XmlDocument();
                                    xmlDocTwo.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.xml"));

                                    //XmlNodeList WhatZipCurrently;
                                    //XmlNodeList whatSearchTerm;

                                    string newValue =Convert.ToString(theNewValue);



                                    XmlNodeList node;
                                    XmlNodeList node2;

                                    node = xmlDocTwo.GetElementsByTagName("ZipCodeCount");

                                    //XmlNode node = xmlDoc.SelectSingleNode("Root/Configuration/ZipCodeCount");
                                    node.Item(0).InnerText = newValue;

                                    int thisValue =Convert.ToInt32(newValue);

                                    node2 = xmlDocTwo.GetElementsByTagName("theZipCodeRow");
                                    node2.Item(0).InnerText = theZipCodesList[thisValue].ToString();

                                    xmlDocTwo.Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.xml"));

                                   


                                    //ConfigurationManager.RefreshSection("appSettings");

                                    //MySqlConnection testNP = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                                    //testNP.Open();

                                    //string InserNEwCM = "INSERT INTO Mesh_Post (Post_Title ,Post_Date,Post_Link,Post_ImgURL,Post_Description,Post_Zip_Locale,UserNo,CategoryTitle) Values ('" + j + "','date','url','imageurl','thenisp','78045',320,'Restaurants')";
                                    //MySqlCommand cmdFinal = new MySqlCommand(InserNEwCM, testNP);

                                    //cmdFinal.ExecuteNonQuery();
                                    //testNP.Clos+6e();


                                    //   goto SearchAgain;

                                }
                            }

                        }
                        catch (Exception theE)
                        {
                            if (theE.Message == "The remote server returned an error: (403) Forbidden.")
                            {
                                return;
                            }
                            else
                            {

                                   
                                                                                                
                            }
                        }

                        
                    }
                    testCon.Close();
                    testConTwo.Close();
                    
                }


            }
            catch (Exception newExcept)
            {
               // throw newExcept.InnerException;



            }

        }


        internal class MyJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {

                //MySqlConnection testNP = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                //testNP.Open();

                //string InserNEwCM = "INSERT INTO Mesh_Post (Post_Title ,Post_Date,Post_Link,Post_ImgURL,Post_Description,Post_Zip_Locale,UserNo,CategoryTitle) Values ('5','date','url','imageurl','thenisp','78045',320,'Restaurants')";
                //MySqlCommand cmdFinal = new MySqlCommand(InserNEwCM, testNP);

                //cmdFinal.ExecuteNonQuery();
                //testNP.Close();
                RequestPosts();

                // RequestPosts(); 
                //RequestPosts();

                // //const string zwsid = "X1-ZWz1dfzozk5amj_6jziz";
                //String url = "http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=X1-ZWz1dfzozk5amj_6jziz&citystatezip=78041";
                //HttpWebRequest Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);

                //string conString = "";

                //if (ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString() != "")
                //{

                //    MySqlConnection testCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                //    testCon.Open();

                //    Random random = new Random();
                //    int num = random.Next(1000);

                //    string cmdText = "INSERT INTO Mesh_Category (CategoryTitle ,CategoryDescription) Values ('" + num + "','CatDesc')";
                //    MySqlCommand cmd = new MySqlCommand(cmdText, testCon);
                //    cmd.ExecuteNonQuery();

                //    testCon.Close();

                //}

            }
        }

        public static void AddJob()
        {

            IJob myJob = new MyJob();
            JobDetailImpl jobDetail = new JobDetailImpl("Purge", "Group1", myJob.GetType());

            //  CronTriggerImpl trigger = new CronTriggerImpl("Trigger1", "Group1", "When to run it goes here");
            SimpleTriggerImpl trigger1 = new SimpleTriggerImpl("Trigger2", 950, TimeSpan.FromDays(1.00));
            //trigger1.SetNextFireTimeUtc(SystemTime.UtcNow());
            _scheduler.ScheduleJob(jobDetail, trigger1);

              // create job
         
  
            //    DateTimeOffset? nextFireTime = trigger.GetNextFireTimeUtc();
            //  Console.WriteLine("Next Fire Time:" + nextFireTime.Value);
        }


        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}